import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  Checkbox,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  Radio,
  Select,
  Space
} from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equTicketAdd,
  equTicketGet,
  equTicketUpdate
} from '@/services/bizApi/shebaogongzuopiaojiekou';
import { equDefectGet } from '@/services/bizApi/shebaoquexianjiekou';
import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';
import Defect, { DefectRef } from './defect';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const defect = useRef<DefectRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [dataSource, setDataSource] = useState<BIZAPI.EquInfoEntity[]>([]);

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const equTicket = useRequest(
    async (id: string) => {
      const res = await equTicketGet({ id });
      form.setFieldsValue({
        ...res?.data,
        dangerPoint: res?.data?.dangerPoint?.split(','),
        protectiveMeasure: res?.data?.protectiveMeasure?.split(','),
        maintenancePlan: res?.data?.maintenancePlanBeginTime
          ? [dayjs(res?.data?.maintenancePlanBeginTime), dayjs(res?.data?.maintenancePlanEndTime)]
          : undefined,
        safetyMeasure: res?.data?.safetyMeasure?.replace(/,/g, ' /n ')
      });
      if (res?.data?.defectId) {
        setDataSource([{ id: res?.data?.defectId }]);
      }
      return res?.data;
    },
    {
      manual: true
    }
  );

  const equDefect = useRequest(
    async (id: string) => {
      const res = await equDefectGet({ id });
      form.setFieldsValue({
        ...res?.data,
        ...res?.data?.detail,
        workTask: `${res?.data?.equipmentName}${res?.data?.equipmentLocation ? '-' + res?.data?.equipmentLocation : ''}`,
        dangerPoint: res?.data?.detail?.dangerPoint?.split(','),
        protectiveMeasure: res?.data?.detail?.protectiveMeasure?.split(','),
        maintenancePlan: res?.data?.maintenancePlanBeginTime
          ? [dayjs(res?.data?.maintenancePlanBeginTime), dayjs(res?.data?.maintenancePlanEndTime)]
          : undefined
      });
      return res?.data;
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        maintenanceLeaderName: userInfo?.data?.filter(
          (item) => item.id === values?.maintenanceLeaderId
        )?.[0]?.fullName,
        maintenancePlanBeginTime: values?.maintenancePlan?.[0]
          ? dayjs(values?.maintenancePlan?.[0]).format('YYYY-MM-DD HH:mm')
          : undefined,
        maintenancePlanEndTime: values?.maintenancePlan?.[1]
          ? dayjs(values?.maintenancePlan?.[1]).format('YYYY-MM-DD HH:mm')
          : undefined,
        dangerPoint: values?.dangerPoint?.join(','),
        protectiveMeasure: values?.protectiveMeasure?.join(','),
        defectId: dataSource?.[0]?.id ? dataSource?.[0]?.id : undefined
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      if (args?.type === 'add') {
        await equTicketAdd(query);
      }
      if (args?.type === 'edit') {
        await equTicketUpdate(query);
      }
      // await (args?.type === 'edit' ? safePlanInfoUpdate(query) : safePlanInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            equTicket.run(arg?.rowData?.id as unknown as string);
            // 回填数据
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增安全计划',
          edit: '编辑安全计划',
          detail: '安全计划详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      {/* <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          width: '100%',
          padding: '20px 24px 10px'
        }}
      >
        <Button
          type="primary"
          disabled={args?.type === 'detail'}
          onClick={() => {
            defect.current?.open({
              onSuccess: (rows) => {
                // form?.setFieldsValue({
                //   equipmentName: rows?.[0]?.equipmentName,
                //   equipmentCode: rows?.[0]?.equipmentCode,
                //   equipmentLocation: rows?.[0]?.storageLocation
                // });
                setDataSource(rows || []);
                equDefect.run(rows?.[0]?.id as unknown as string);
              }
            });
          }}
        >
          缺陷关联
        </Button>
      </div> */}
      {/* 缺陷关联 */}
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        labelWrap
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="单位"
          name="maintenanceUnit"
          rules={[
            {
              required: false,
              message: '请输入单位'
            }
          ]}
        >
          <Input
            style={{ width: '100%' }}
            placeholder="请输入单位"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          hidden
          label="缺陷单号"
          name="defectNo"
          rules={[
            {
              required: false,
              message: '请输入缺陷单号'
            }
          ]}
        >
          <Input
            style={{ width: '100%' }}
            placeholder="请输入缺陷单号"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          hidden
          label="缺陷类型"
          name="defectType"
          rules={[
            {
              required: false,
              message: '请选择缺陷类型'
            }
          ]}
        >
          <Select
            // disabled={!!dataSource?.length}
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择缺陷类型"
            options={[
              {
                label: '设备缺陷',
                value: 1
              },
              {
                label: '生成缺陷',
                value: 2
              }
            ]}
          />
        </Form.Item>
        <ProFormSelect
          name="maintenanceLeaderId"
          label="工作负责人"
          // disabled={!!dataSource?.length}
          placeholder="请选择工作负责人"
          showSearch={true}
          rules={[{ required: true, message: '请选择工作负责人' }]}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });

            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="班组"
          name="maintenance"
          rules={[
            {
              required: false,
              message: '请输入班组'
            }
          ]}
        >
          <Input
            style={{ width: '100%' }}
            placeholder="请输入班组"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="工作班组人员"
          name="maintenanceMember"
          rules={[
            {
              required: false,
              message: '请输入工作班组人员'
            }
          ]}
        >
          <Input.TextArea
            style={{ width: '100%' }}
            placeholder="请输入工作班组人员"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="工作任务"
          name="workTask"
          rules={[
            {
              required: true,
              message: '请输入工作任务'
            }
          ]}
        >
          <Input.TextArea
            style={{ width: '100%' }}
            placeholder="请输入工作任务"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="工作内容"
          name="defectDescription"
          rules={[
            {
              required: true,
              message: '请输入工作内容'
            }
          ]}
        >
          <Input.TextArea
            style={{ width: '100%' }}
            placeholder="请输入工作内容"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="计划时间"
          name="maintenancePlan"
          rules={[
            {
              required: true,
              message: '请选择计划时间'
            }
          ]}
        >
          <DatePicker.RangePicker
          // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="危险点"
          name="dangerPoint"
          rules={[
            {
              required: false,
              message: '请选择危险点'
            }
          ]}
        >
          <Checkbox.Group
            // disabled={!!dataSource?.length}
            options={[
              {
                label: '火灾、爆炸',
                value: '火灾、爆炸'
              },
              {
                label: '机械伤害',
                value: '机械伤害'
              },
              {
                label: '物体打击',
                value: '物体打击'
              },
              {
                label: '酸碱灼烫',
                value: '酸碱灼烫'
              },
              {
                label: '淹溺',
                value: '淹溺'
              },
              {
                label: '登高、临边作业',
                value: '登高、临边作业'
              },
              {
                label: '起重伤害',
                value: '起重伤害'
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="预控措施"
          name="protectiveMeasure"
          rules={[
            {
              required: false,
              message: '请选择预控措施'
            }
          ]}
        >
          <Checkbox.Group
            // disabled={!!dataSource?.length}
            options={[
              {
                label:
                  '正确穿戴好个人防护用品，准备好灭火器材，防火布隔离动火位置，清理干净周边易燃可燃物',
                value:
                  '正确穿戴好个人防护用品，准备好灭火器材，防火布隔离动火位置，清理干净周边易燃可燃物'
              },
              {
                label: '确认设备断电、停用后，再检维修；维修过程上锁挂牌',
                value: '确认设备断电、停用后，再检维修；维修过程上锁挂牌'
              },
              {
                label: '通风后，检测可燃气体浓度，合格后才能动火',
                value: '通风后，检测可燃气体浓度，合格后才能动火'
              },
              {
                label: '正确穿戴好个人防护用品，隔绝酸碱液体，防飞溅伤人',
                value: '正确穿戴好个人防护用品，隔绝酸碱液体，防飞溅伤人'
              },
              {
                label: '正确穿戴好个人防护用品，备好救生圈，救生绳',
                value: '正确穿戴好个人防护用品，备好救生圈，救生绳'
              },
              {
                label: '正确穿戴好个人防护用品（安全帽、五点式全身安全带），防止高处坠落',
                value: '正确穿戴好个人防护用品（安全帽、五点式全身安全带），防止高处坠落'
              },
              {
                label: '起重设备须持证人员操作；洗膜过程专人旁站监护',
                value: '起重设备须持证人员操作；洗膜过程专人旁站监护'
              }
            ]}
          />
        </Form.Item>
        {/* <Form.Item
          label="其他危险点"
          name="dangerPointOther"
          rules={[
            {
              required: false,
              message: '请输入其他危险点'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入其他危险点"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="其他预控措施"
          name="protectiveMeasureOther"
          rules={[
            {
              required: false,
              message: '请输入其他预控措施'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入其他预控措施"
            // disabled={!!dataSource?.length}
          />
        </Form.Item> */}
        {/* <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            width: '100%',
            padding: '20px 24px 10px'
          }}
        >
          <div style={{ fontSize: '16px' }}>安全措施详情</div>
        </div> */}

        <Form.Item
          label="安全措施"
          name="safetyMeasure"
          rules={[
            {
              required: false,
              message: '请输入安全措施'
            }
          ]}
        >
          {args?.type === 'detail' ? (
            args.rowData.safetyMeasure ? (
              args.rowData.safetyMeasure.split(',').map((item, index) => (
                <div key={index} style={{ marginBottom: '10px', color: '#bbb' }}>
                  {item}
                </div>
              ))
            ) : (
              ''
            )
          ) : (
            <Input.TextArea
              rows={6}
              style={{ resize: 'none' }}
              placeholder="请输入安全措施"
              // disabled={!!dataSource?.length}
            />
          )}
        </Form.Item>

        {/* <Form.Item
          label="应隔离或停供的能源介质(如水、油、酸碱液体、气体)"
          name="measuresEnergy"
          rules={[
            {
              required: false,
              message: '请输入应隔离或停供的能源介质(如水、油、酸碱液体、气体)'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入应隔离或停供的能源介质(如水、油、酸碱液体、气体)"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="保证工作安全、避免人身伤害的其他有效措施"
          name="measuresSafety"
          rules={[
            {
              required: false,
              message: '请输入保证工作安全、避免人身伤害的其他有效措施'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入保证工作安全、避免人身伤害的其他有效措施"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="应设遮拦、应挂标示牌及其他防止误磋等措施"
          name="measuresWarning"
          rules={[
            {
              required: false,
              message: '请输入应设遮拦、应挂标示牌及其他防止误磋等措施'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入应设遮拦、应挂标示牌及其他防止误磋等措施"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="其他需特别提醒的安全措施"
          name="measuresExtra"
          rules={[
            {
              required: false,
              message: '请输入其他需特别提醒的安全措施'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入其他需特别提醒的安全措施"
            // disabled={!!dataSource?.length}
          />
        </Form.Item>
        <Form.Item
          label="具体内容"
          name="measuresContent"
          rules={[
            {
              required: false,
              message: '请输入具体内容'
            }
          ]}
        >
          <Input.TextArea
            placeholder="请输入具体内容"
            // disabled={!!dataSource?.length}
          />
        </Form.Item> */}
        {args?.type === 'detail' && args!.rowData.ticketStatus === 50 ? (
          <>
            <Form.Item label="是否违规" name="illegal">
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
            {args?.rowData?.illegal === true && (
              <>
                <ProFormSelect
                  name="illegalTeamId"
                  label="违规班组"
                  placeholder=""
                  rules={[{ required: true, message: '请选择违规班组' }]}
                  request={async () => {
                    const res = await proShiftTeamPage({
                      page: 1,
                      size: 1000
                    });
                    return (
                      res.data?.records?.map((item) => ({
                        value: item.id,
                        label: item.name
                      })) || []
                    );
                  }}
                />
                <ProFormSelect
                  name="illegalUserId"
                  label="违规人员"
                  placeholder=""
                  rules={[{ required: true, message: '请选择违规人员' }]}
                  request={async () => {
                    const res = await orgUserInfoVoPage({
                      page: 1,
                      size: 1000
                    });

                    return (
                      res?.data?.records?.map((item) => {
                        return {
                          label: item?.fullName,
                          value: item?.id
                        };
                      }) || []
                    );
                  }}
                />
                <Form.Item label="违规原因" name="illegalReason">
                  <Input.TextArea></Input.TextArea>
                </Form.Item>
              </>
            )}
          </>
        ) : (
          ''
        )}
      </Form>
      {/* 缺陷关联 */}
      <Defect ref={defect} />
    </Drawer>
  );
};

export default forwardRef(Edit);
